package com.um.jdy.tcp.cmd;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.um.jdy.tcp.netty.NettyContextHolder;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 邓南辉
 * 日期 2023/8/28
 * 版权所有 广州优匠科技有限公司
 */
@Component
@Slf4j
public class SDKCommandSender implements CommandSender{

    @Autowired
    protected CommandLogs commandLogs;

    @Autowired
    protected SDKCommandParser sdkCommandParser;

    private final Map<String, Long> lastSendTimes = new ConcurrentHashMap<>();

    @Async
    @Override
    public void sendCmd(String imei, SDKCommand command) {
        try {
            ChannelHandlerContext ctx = NettyContextHolder.getDeviceContext(imei);
            if(ctx == null){
                log.warn("设备{}已离线！", imei);
                return;
            }

            // 同一个设备，距离上次调用需间隔1秒，防止调用过快设备无法解析
            Long lastSendTime = lastSendTimes.put(imei, System.currentTimeMillis());
            if (lastSendTime != null) {
                long diff = System.currentTimeMillis() - lastSendTime;
                if (diff >= 0 && diff < 1000) {
                    ThreadUtil.sleep(1000 - diff);
                }
            }
            ctx.writeAndFlush(sdkCommandParser.toCommandString(command)).addListener(future -> {
                log.debug("发送命令{}：{}", future.isSuccess() ? "成功" : "失败", sdkCommandParser.toCommandString(command));
                Date time = DateUtil.date();
                lastSendTimes.put(imei, time.getTime());
                commandLogs.addLogs(imei, command, sdkCommandParser.toCommandString(command), time,future.isSuccess());
            });


        } catch (Exception e) {
            log.error("sendClient异常", e);
        }
    }
}
